using AutoMapper;
using Microsoft.AspNetCore.Hosting;
using Newtonsoft.Json;
using SX.BaseService.Repository.Core;
using SX.BaseService.Repository.Entity;
using SX.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SX.BaseService.Service
{
    /// <summary>
	/// SysConfig服务层
	/// </summary>
    public class SysConfigService:DbContext,ISysConfigService
    {
        private readonly IRepository<SysConfigEntity> _repository;
        private readonly IMapper _mapper;
        private readonly IWebHostEnvironment _webHostEnvironment;

        public SysConfigService(IRepository<SysConfigEntity> repository,IMapper mapper,IWebHostEnvironment webHostEnvironment)
        {
            _webHostEnvironment = webHostEnvironment;
            _mapper = mapper;
            _repository = repository;
        }

        public enum SettingType
        {
            [Description("基本信息")]
            Base = 0,
            [Description("短信设置")]
            Smms = 1,
            [Description("邮件设置")]
            Mail = 2,
            [Description("文件上传配置")]
            FileUpload = 3
        }
        public async Task<IApiResult> Add(ConfigAddModel model)
        {
            await Db.Deleteable<SysConfigEntity>().ExecuteCommandAsync();
            var uploadCof = new UploadConfig(_webHostEnvironment.WebRootPath);
            var baseSetting = _mapper.Map<BaseSetting>(model);
            if (model.FileUrl.IsNull())
            {
                //保存文件
                var result = await FileUploadHelper.UploadAsync(model.file, uploadCof, "Logo");
              
                if (result.Success)
                {
                    baseSetting.Logo = result.Data;
                }
            }
            else
            {
                baseSetting.Logo = model.FileUrl;
            }
          
            var mailSetting = _mapper.Map<MailSetting>(model);
            var sMSSSetting = _mapper.Map<SMSSetting>(model);
            var fileUploadSetting = _mapper.Map<FileUploadSetting>(model);
            //更新或者新增
            var json_base = baseSetting.ToJson();
            var json_mail = mailSetting.ToJson();
            var json_smms = sMSSSetting.ToJson();
            var json_file = fileUploadSetting.ToJson();
            List<SysConfigEntity> list_add = new List<SysConfigEntity>();
            List<SysConfigEntity> list_update = new List<SysConfigEntity>();
            SysConfigEntity baseEntity = new SysConfigEntity
            {
                Id=GuidHelper.NewSequentialGuid(SequentialGuidType.SequentialAtEnd),
                Code =SettingType.Base.To_String(),
                Value = json_base,
                Remarks="系统基本设置"
            };
            SysConfigEntity mail = new SysConfigEntity
            {
                Id = GuidHelper.NewSequentialGuid(SequentialGuidType.SequentialAtEnd),
                Code = SettingType.Mail.To_String(),
                Value = json_mail,
                Remarks = "邮件设置"
            };
            SysConfigEntity smms = new SysConfigEntity
            {
                Id = GuidHelper.NewSequentialGuid(SequentialGuidType.SequentialAtEnd),
                Code = SettingType.Smms.To_String(),
                Value = json_smms,
                Remarks="短信设置"
            };
            SysConfigEntity file = new SysConfigEntity
            {
                Id = GuidHelper.NewSequentialGuid(SequentialGuidType.SequentialAtEnd),
                Code =SettingType.FileUpload.To_String(),
                Value = json_file,
                Remarks="文件上传设置"
            };
            list_add.Add(baseEntity);
            list_add.Add(mail);
            list_add.Add(smms);
            list_add.Add(file);
            var res = await _repository.Add(list_add);
            if (res < 0) return ApiResult.NotOk("新增失败");
            return ApiResult.Ok();
        }

        public async Task<IApiResult> Query()
        {
            var configModel = new ConfigAddModel();
            var list = await _repository.GetAll();
            foreach(var item in list)
            {
               
                if (item.Code == SettingType.Base.ToString())
                {
                    var temp=  JsonConvert.DeserializeObject<BaseSetting>(item.Value);
                    configModel.SystemName = temp.SystemName;
                    configModel.SystemIntroduction = temp.SystemIntroduction;
                    configModel.PSRecordNum = temp.PSRecordNum;
                    configModel.ICPRecordNum = temp.ICPRecordNum;
                    configModel.Logo = temp.Logo;
                    configModel.DomainName = temp.DomainName;
                    configModel.Company = temp.Company;
                    configModel.Adress = temp.Adress;
                    configModel.Phone = temp.Phone;
                    configModel.Email = temp.Email;

                }
                else if (item.Code == SettingType.FileUpload.To_String())
                {
                   var  temp= JsonConvert.DeserializeObject<FileUploadSetting>(item.Value);
                    configModel.FilePath = temp.FilePath;
                    configModel.Server = temp.Server;
                    configModel.Ext = temp.Ext;
                }
                else if (item.Code == SettingType.Mail.To_String())
                {
                   var temp= JsonConvert.DeserializeObject<MailSetting>(item.Value);
                    configModel.SMTPIP = temp.SMTPIP;
                    configModel.SMTPPort = temp.SMTPPort;
                    configModel.ISSSLEncrypt = temp.ISSSLEncrypt;
                    configModel.SendMailAdress = temp.SendMailAdress;
                    configModel.MailPwd = temp.MailPwd;
                    configModel.MailUserName = temp.MailUserName;
                    configModel.NickName = temp.NickName;

                }
                else if (item.Code == SettingType.Smms.To_String())
                {
                   var temp= JsonConvert.DeserializeObject<SMSSetting>(item.Value);
                    configModel.APIAdress = temp.APIAdress;
                    configModel.LoginUserName = temp.LoginUserName;
                    configModel.SecretKey = temp.SecretKey;
                }
                //configModel = _mapper.Map<ConfigAddModel>(temp);
            }

            return ApiResult.Ok(configModel);

        }
    }
}